import { Injectable, Logger } from '@nestjs/common';
import FdfsClient from './lib/client';
import { env } from '~/global/env';
import { MultipartFile } from '@fastify/multipart';
import { getExtname } from '~/utils/file.util';

@Injectable()
export class FastdfsService {
  private readonly logger: Logger = new Logger(FastdfsService.name);

  private client: FdfsClient;
  private readonly fastDfsServer: string = env('FASTDFS_TRACKER_SERVER');

  // 实现一创建则初始化
  constructor() {
    this.client = new FdfsClient({
      trackers: [
        {
          host: env('FASTDFS_TRACKER_HTTP_HOST'),
          port: Number(env('FASTDFS_TRACKER_HTTP_PORT')),
        },
      ],
    });
  }

  /**
   * 上传文件
   * @param file 文件路径
   */
  async upload(file: MultipartFile): Promise<{ fileId: string; path: string }> {
    return this.uploadByBuffer(await file.toBuffer(), getExtname(file.filename));
  }

	/**
	 * 上传文件
	 * @param buffer 文件Buffer
	 * @param extName 文件后缀名
	 */
  async uploadByBuffer(buffer: Buffer, extName: string): Promise<{ fileId: string; path: string }> {
    return new Promise(async (resolve, reject) => {
      this.client
        .upload(buffer, { ext: extName })
        .then((fileId: string) => {
          this.logger.debug(`fileId: ${fileId}`);

          // 获取文件的URL
          const path = `${this.fastDfsServer}${fileId}`;

          resolve({ fileId, path });
        })
        .catch((err: any) => {
          reject(err);
        });
    });
  }

  /**
   * 删除文件
   * @param fileId 文件ID
   */
  async delete(fileId: string): Promise<void> {
    return new Promise((resolve, reject) => {
      this.client
        .del(fileId)
        .then(() => {
          resolve();
        })
        .catch((err: any) => {
          reject(err);
        });
    });
  }
}
